package com.hqd.ch03.test.web.v37;


import com.hqd.ch03.v37.context.stereotype.Controller;
import com.hqd.ch03.v37.web.bind.annotation.RequestMapping;
import com.hqd.ch03.v37.web.bind.annotation.RequestMethod;
import com.hqd.ch03.v37.web.bind.annotation.RequestParam;
import com.hqd.ch03.v37.web.multipart.MultipartFile;
import com.hqd.ch03.v37.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
public class HelloController {
    @RequestMapping("/gotoUpload")
    public String gotoUpload(HttpServletRequest req, HttpServletResponse resp) {
        return "upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView handleFileUpload(@RequestParam("file") MultipartFile file) {
        ModelAndView modelAndView = new ModelAndView("hello");
        if (!file.isEmpty()) {
            try {
                // 保存文件
                String fileName = file.getOriginalFilename();
                File serverFile =
                        new File("E:\\代码\\java\\JavaEE\\spring-imitation\\src\\main\\resources\\v37\\uploads\\" + fileName);
                file.transferTo(serverFile);
                modelAndView.addObject("message", "File uploaded successfully: " + fileName);
            } catch (IOException e) {
                e.printStackTrace();
                modelAndView.addObject("message", "File upload failed: " + e.getMessage());
            }
        } else {
            modelAndView.addObject("message", "Please select a file to upload.");
        }
        return modelAndView;
    }
}
